package com.daxia.bumall.web.controller.m;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.DecorateNoteType;
import com.daxia.bumall.common.DecorateNoteUserType;
import com.daxia.bumall.common.MyJSONObject;
import com.daxia.bumall.common.NeedLogin;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.DecorateNoteClickDTO;
import com.daxia.bumall.dto.DecorateNoteCommentDTO;
import com.daxia.bumall.dto.DecorateNoteDTO;
import com.daxia.bumall.dto.DecorateNoteDetailDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.exception.BizException;
import com.daxia.bumall.model.DecorateNote;
import com.daxia.bumall.model.DecorateNoteComment;
import com.daxia.bumall.model.DecorateNoteDetail;
import com.daxia.bumall.model.Designer;
import com.daxia.bumall.model.User;
import com.daxia.bumall.support.MPage;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.DateUtils;

@Controller
@RequestMapping(value = "/m/decorateNote", produces = "application/json;charset=UTF-8")
public class MDecorateNoteController extends MBaseController {
	
	private static Logger logger = Logger.getLogger(MDecorateNoteController.class);
    
    @ResponseBody
    @RequestMapping("list")
    public String list(DecorateNoteDTO dto, MPage page) throws Exception {
    
    	if (dto.getUser() == null && dto.getTarget() == null) {
    		dto.setShow(true);
    	}
    	
        List<DecorateNoteDTO> decorateNoteDTOs = decorateNoteService.find(dto, page);
        MyJSONObject data = new MyJSONObject();
        JSONArray decorateNoteInfos = new JSONArray();
        for (DecorateNoteDTO decorateNoteDTO : decorateNoteDTOs) {
        	MyJSONObject decorateNoteInfo = getDecorateNoteJSONObject(decorateNoteDTO);
        	
        	decorateNoteInfos.add(decorateNoteInfo);
        }
        
        data.put("decorateNoteInfos", decorateNoteInfos);
        setPageInfo(data, page);

        return toJson(data);
    }
    


	private MyJSONObject getDecorateNoteJSONObject(DecorateNoteDTO decorateNoteDTO) {
		//String headImage = getHeadImage(decorateNoteDTO);
	
		MyJSONObject decorateNoteInfo = new MyJSONObject();
		decorateNoteInfo.put("id", decorateNoteDTO.getId());
		decorateNoteInfo.put("headImage", decorateNoteDTO.getHeadImage());
		decorateNoteInfo.put("title", decorateNoteDTO.getTitle());
		decorateNoteInfo.put("subTitle", decorateNoteDTO.getSubTitle());
		decorateNoteInfo.put("mobile", decorateNoteDTO.getMobile());
		decorateNoteInfo.put("clickCount", decorateNoteDTO.getClickCount());
		decorateNoteInfo.put("rate", decorateNoteDTO.getRate());
		
		MyJSONObject ownerInfo = new MyJSONObject();
		
		if (decorateNoteDTO.getUser().getType().intValue() == DecorateNoteUserType.NomalUser.getValue()) {
			ownerInfo.put("id", decorateNoteDTO.getTarget().getId());
			ownerInfo.put("username", decorateNoteDTO.getTarget().getUsername());
			ownerInfo.put("nickName", decorateNoteDTO.getTarget().getNickName());
			ownerInfo.put("headImage", decorateNoteDTO.getTarget().getHeadImage());
			ownerInfo.put("userType", UserType.Normal.getValue());
			ownerInfo.put("level", null);
			ownerInfo.put("levelRemark", "");
		}
		
		if (decorateNoteDTO.getUser().getType().intValue() == DecorateNoteUserType.DesignerUser.getValue()) {
			ownerInfo.put("id", decorateNoteDTO.getDesigner().getUser().getId());
			ownerInfo.put("username", decorateNoteDTO.getDesigner().getUser().getUsername());
			ownerInfo.put("nickName", decorateNoteDTO.getDesigner().getUser().getNickName());
			ownerInfo.put("headImage", decorateNoteDTO.getDesigner().getUser().getHeadImage());
			ownerInfo.put("userType", UserType.Designer.getValue());
			ownerInfo.put("level", null);
			ownerInfo.put("levelRemark", "高级设计师");
		}
		
		JSONArray decorateNoteCommentInfos = new JSONArray();
		DecorateNoteCommentDTO decorateNoteCommentQuery = new DecorateNoteCommentDTO();
		DecorateNote decorateNote = new DecorateNote();
		BeanUtils.copyProperties(decorateNoteDTO, decorateNote);
		decorateNoteCommentQuery.setDecorateNote(decorateNote );
		Page decorateCommentPage = new Page();
		List<DecorateNoteCommentDTO> decorateNoteComments = decorateNoteCommentService.find(decorateNoteCommentQuery , decorateCommentPage );
		for (DecorateNoteComment decorateNoteComment : decorateNoteComments) {
			JSONObject decorateNoteCommentInfo = new JSONObject();
			decorateNoteCommentInfo.put("id", decorateNoteComment.getId());
			decorateNoteCommentInfo.put("detail", decorateNoteComment.getDetails());
			decorateNoteCommentInfo.put("username", decorateNoteComment.getUser().getUsername());
			decorateNoteCommentInfo.put("nickName", decorateNoteComment.getUser().getNickName());
			decorateNoteCommentInfo.put("userId", decorateNoteComment.getUser().getId());
			String imgs[] = {};
			String images = decorateNoteComment.getImages();
			if (StringUtils.isNotBlank(images)) {
				imgs = images.split(",");
			}
			decorateNoteCommentInfo.put("image", imgs);
			decorateNoteCommentInfo.put("createTime", DateUtils.format(decorateNoteComment.getCreateTime(), "yyyy-MM-dd"));
			decorateNoteCommentInfos.add(decorateNoteCommentInfo);
		}
		
		decorateNoteInfo.put("decorateNoteCommentInfos", decorateNoteCommentInfos);
		decorateNoteInfo.put("ownerInfo", ownerInfo);
		return decorateNoteInfo;
	}
    
    @ResponseBody
    @RequestMapping("detail")
    public String detail(Long id) throws Exception {
    	
    	DecorateNoteDTO decorateNoteDTO = decorateNoteService.load(id);
    	
    	MyJSONObject data = getDecorateNoteJSONObject(decorateNoteDTO);
    	JSONArray decorateNoteDetailInfos = new JSONArray();
    	List<DecorateNoteDetail> decorateNoteDetails = decorateNoteDTO.getDecorateNoteDetails();
    	for (DecorateNoteDetail decorateNoteDetail : decorateNoteDetails) {
    		MyJSONObject decorateNoteDetailInfo = new MyJSONObject();
    		String images = decorateNoteDetail.getImages();
    		String[] imgs = images.split(",");
     		decorateNoteDetailInfo.put("id", decorateNoteDetail.getId());
    		decorateNoteDetailInfo.put("images", imgs);
    		decorateNoteDetailInfo.put("type", decorateNoteDetail.getType());
    		decorateNoteDetailInfo.put("typeRemark", DecorateNoteType.getByValue(decorateNoteDetail.getType()).getRemark());
    		decorateNoteDetailInfo.put("createTime", DateFormatUtils.format(decorateNoteDetail.getCreateTime(), "yyyy-MM-dd"));
    		decorateNoteDetailInfo.put("detail", decorateNoteDetail.getDetails());
    		
    		decorateNoteDetailInfos.add(decorateNoteDetailInfo);
    	}
    	data.put("decorateNodeDetailInfos", decorateNoteDetailInfos);
    	return toJson(data);
    }
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("save")
    public String save(String decorateNoteId, String title, String subTitle, Integer type, String details, String mobile, HttpServletRequest request) throws Exception {
    	if (type == null) {
    		throw new BizException("软装笔记类型不能为空！");
    	}
    	UserDTO currentUser = getCurrentUserDTO();
    	User user = new User();
    	BeanUtils.copyProperties(currentUser, user);
    	
    	DecorateNoteDetailDTO decorateNoteDetailDTO = new DecorateNoteDetailDTO();
    	DecorateNoteDTO decorateNoteDTO = null;
    	if (StringUtils.isNotBlank(decorateNoteId)) {
    		decorateNoteDTO = decorateNoteService.load(Long.parseLong(decorateNoteId));
    	} else {
    		decorateNoteDTO = new DecorateNoteDTO();
    		decorateNoteDTO.setClickCount(0L);
        	decorateNoteDTO.setRate(0.0);
        	decorateNoteDTO.setCreateTime(new Date());
        	decorateNoteDTO.setUser(user);
        	Designer designer = null;
        	if (CollectionUtils.isNotEmpty(user.getDesigners())) {
        		designer = user.getDesigners().get(0);
        	}
        	decorateNoteDTO.setDesigner(designer);
        	
        	UserDTO target = null;
        	if (StringUtils.isNotBlank(mobile)) { // 设计师用户软装日记
        		target = userService.findByMobile(mobile);
        		decorateNoteDTO.setTarget(target);
        		decorateNoteDTO.setMobile(mobile);
        	} 
        	if (target == null) {
        		throw new BizException("手机号" + mobile + "用户不存在") ;
        	}
        	if (StringUtils.isNotBlank(title)) {
        		decorateNoteDTO.setTitle(title);
        	}
        	if (StringUtils.isNotBlank(subTitle)) {
        		decorateNoteDTO.setSubTitle(subTitle);
        	}
    	}
    	
    	String fileUrl = super.saveFilesAndReturnFileName(request);
    	String[] imgs = fileUrl.split(",");
    	if (imgs.length > 0) {
    		decorateNoteDTO.setHeadImage(imgs[0]);
    	}
    	
    	decorateNoteDetailDTO.setType(type);
    	decorateNoteDetailDTO.setDetails(details);
    	decorateNoteDetailDTO.setCreateTime(new Date());
    	
    	
    	decorateNoteDetailDTO.setImages(fileUrl);
    	if (type.intValue() == DecorateNoteType.Rated.getValue()) {
    		decorateNoteDTO.setShow(true);
    	} else {
    		decorateNoteDTO.setShow(false);
    	}
    	if (decorateNoteDTO.getId() == null) {
    		Long dnId = decorateNoteService.create(decorateNoteDTO);
    		decorateNoteDTO.setId(dnId);
    	} else {
    		decorateNoteService.updateAllFields(decorateNoteDTO);
    	}
    	
    	
    	decorateNoteDetailDTO.setDecorateNote(decorateNoteDTO);
    	decorateNoteDetailService.create(decorateNoteDetailDTO);
    	return toJson();
    }
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("comment")
    public String comment(String decorateNoteId, String comment, Double rate, HttpServletRequest request) throws Exception {
    	super.assertNotBlank(decorateNoteId, "软装笔记ID不能为空！");
    	
    	UserDTO currentUser = getCurrentUserDTO();
    	User user = new User();
    	BeanUtils.copyProperties(currentUser, user);
    	
    	String images = super.saveFilesAndReturnFileName(request);
    	
    	DecorateNoteDTO decorateNoteDTO = decorateNoteService.load(Long.parseLong(decorateNoteId));
    	
    	decorateNoteDTO.setShow(true);
    	
    	DecorateNote decorateNote = new DecorateNote();
    	BeanUtils.copyProperties(decorateNoteDTO, decorateNote);
    	
    	DecorateNoteCommentDTO query = new DecorateNoteCommentDTO();
    	query.setDecorateNote(decorateNote);
		List<DecorateNoteCommentDTO> list = decorateNoteCommentService.find(query , null);
		decorateNoteDTO.setRate(Double.valueOf(String.format("%.2f", (rate.doubleValue() + decorateNoteDTO.getRate().doubleValue())/(list.size() + 1))));
		decorateNoteService.updateAllFields(decorateNoteDTO);
    	DecorateNoteCommentDTO decorateNoteCommentDTO = new DecorateNoteCommentDTO();
    	
		decorateNoteCommentDTO.setDecorateNote(decorateNote );
    	decorateNoteCommentDTO.setDetails(comment);
    	decorateNoteCommentDTO.setRate(rate);
    	decorateNoteCommentDTO.setUser(user);
    	decorateNoteCommentDTO.setCreateTime(new Date());
    	decorateNoteCommentDTO.setImages(images);
    	decorateNoteCommentService.create(decorateNoteCommentDTO);
    	
    	return toJson();
    }
    
    
    @ResponseBody
    @RequestMapping("click")
    public String click(String decorateNoteId, String userId) throws Exception {
    	super.assertNotBlank(decorateNoteId, "软装笔记ID不能为空！");
    	
    	DecorateNoteDTO decorateNoteDTO = decorateNoteService.load(Long.parseLong(decorateNoteId));
    	DecorateNote decorateNote = new DecorateNote();
    	BeanUtils.copyProperties(decorateNoteDTO, decorateNote);
    	decorateNoteDTO.setClickCount(decorateNoteDTO.getClickCount() + 1);
    	decorateNoteService.updateAllFields(decorateNoteDTO);
    	
    	User user = null;
    	if (StringUtils.isNotBlank(userId)) {
    		UserDTO userDTO = userService.load(Long.parseLong(userId));
    		user = new User();
    		BeanUtils.copyProperties(userDTO, user);
    	}
    	DecorateNoteClickDTO decorateNoteClickDTO = new DecorateNoteClickDTO();
    	decorateNoteClickDTO.setCreateTime(new Date());
    	decorateNoteClickDTO.setDecorateNote(decorateNote);
    	decorateNoteClickDTO.setUser(user);
		decorateNoteClickService.create(decorateNoteClickDTO ); 
    	
    	return toJson();
    }
    
    private String getHeadImage(DecorateNoteDTO decorateNoteDTO) {
    	DecorateNoteDetail decorateNoteDetail = null;
		String headImage = "";
		List<DecorateNoteDetail> decorateNoteDetails = decorateNoteDTO.getDecorateNoteDetails();
		if (CollectionUtils.isNotEmpty(decorateNoteDetails)) {
			decorateNoteDetail = decorateNoteDetails.get(0);
			String images = decorateNoteDetail.getImages();
			String[] imgs = images.split(",");
			if (imgs.length > 0) {
				headImage = imgs[0];
			}
		}
		
		return headImage;
    }
    
}
